<script>
import { Search } from '@element-plus/icons-vue'
import { defineComponent, reactive, unref } from 'vue'
export default defineComponent({
  name: 'CustomMenu',
  props: {
    menus: {
      type: Array,
      default: () => {
        return []
      }
    },
    collapse: {
      type: Boolean,
      default: false
    },
    uniqueOpened: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const state = reactive({
      queryKey: ''
    })

    const menuSelect = (index) => {
      console.log(index)
    }

    // 渲染菜单的方法
    // defaultActive={unref(activeMenu)}
    const renderMenu = () => {
      if (props.menus && props.menus.length > 0) {
        return (
          <ElMenu
            mode="vertical"
            collapse={props.collapse}
            uniqueOpened={props.uniqueOpened}
            backgroundColor="var(--left-menu-bg-color)"
            textColor="var(--left-menu-text-color)"
            activeTextColor="var(--left-menu-text-active-color)"
            onSelect={menuSelect}
            router={true}
          >
            {{
              default: () => renderMenuItem(unref(props.menus))
            }}
          </ElMenu>
        )
      } else {
        return <div class="menu-no-data">无菜单数据</div>
      }
    }

    const renderMenuName = (name, icon) => {
      return icon ? (
        <>
          <span class="v-menu__title">{name}</span>
        </>
      ) : (
        <span class="v-menu__title">{name}</span>
      )
    }

    const renderMenuItem = (menus) => {
      return menus.map((item) => {
        const { icon, name, href, children } = item
        if (!children || children.length === 0) {
          return (
            <ElMenuItem index={href}>
              {{
                default: () => renderMenuName(name, icon)
              }}
            </ElMenuItem>
          )
        } else {
          return (
            <ElSubMenu index={href}>
              {{
                title: () => renderMenuName(name, icon),
                default: () => renderMenuItem(children)
              }}
            </ElSubMenu>
          )
        }
      })
    }
    return () => (
      <div class="cms-menu-wrap">
        {props.collapse === false ? (
          <div class="cms-menu-query">
            <el-input size="default" v-model={state.queryKey} placeholder="搜索菜单" prefix-icon={Search} />
          </div>
        ) : null}
        <ElScrollbar class="cms-menu-view">{renderMenu(props.menus)}</ElScrollbar>
      </div>
    )
  }
})
</script>

<style lang="scss" scoped>
.cms-menu-wrap {
  padding: 0px;
  box-sizing: border-box;
  flex-grow: 1;
  height: var(--left-menu-height);
  background-color: var(--left-menu-bg-color);
  color: var(--left-menu-text-color);
  .cms-menu-query {
    padding: 5px 10px;
  }
  .cms-menu-view {
    height: calc(100% - 42px);
  }
  .menu-no-data {
    margin-top: 20px;
    text-align: center;
  }
  .el-menu {
    border-right-width: 0px;
  }
}
</style>
